package com.jinghao.tws.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.jinghao.core.common.exception.JingHaoCustomerException;
import com.jinghao.core.common.service.impl.JingHaoBaseServiceImpl;
import com.jinghao.core.common.util.cnd.JhCnd;
import com.jinghao.core.common.util.cnd.JhUpdate;
import com.jinghao.tws.entity.WvCamera.EWvCamera;
import com.jinghao.tws.entity.WvCamera;
import com.jinghao.tws.entity.WvFlow;
import com.jinghao.tws.entity.WvFlow.EWvFlow;
import com.jinghao.tws.entity.WvUploadTaskInfo.EWvUploadTaskInfo;
import com.jinghao.tws.entity.WvProcessConfig;
import com.jinghao.tws.entity.WvUploadTaskInfo;
import com.jinghao.tws.service.IWvFlowService;
import com.jinghao.tws.service.IWvProcessConfigService;
import com.jinghao.tws.service.IWvUploadTaskInfoService;
import com.jinghao.tws.util.EJhTwsCode;

@Service("wvFlowService")
public class WvFlowServiceImpl extends JingHaoBaseServiceImpl<WvFlow> implements IWvFlowService {
	//==================定制内容开始======================
//在这里修改代码
	@Resource
	private IWvProcessConfigService wvProcessConfigService;
	
	@Resource
	private IWvUploadTaskInfoService wvUploadTaskInfoService;
	
	@Override
	public String checkWvFlowIsExists(String code) {
		WvFlow model=new WvFlow();
		JhCnd cnd=new JhCnd();
		cnd.andEquals("code");
		model.lnkCnd(cnd);
		model.setCode(code);
		List<Map<String,Object>> list =this.queryMapListById(model, "checkWvFlowIsExists");
		if(list==null||list.size()<=0||list.size()>1){
			return null;
		}
		return list.get(0).get("flowUuid").toString();
	}
	
	/**
	 * 流程列表（包含模糊查询）
	 */
	@Override
	public void listWvFlow(WvFlow model) {
		/*if (StringUtils.isEmpty(model.getName())) {
			throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请输入流程名称！");
		}*/
		JhCnd cnd=new JhCnd();
		cnd.andNotEquals("status");
		model.setStatus(EWvFlow.status_2.getKey());
		if(model.getName() != null && !model.getName().trim().equals("")){
			cnd.andLike("name");
			model.setName("%"+model.getName()+"%");
		}
		model.lnkCnd(cnd);
		model.setMapList(this.queryMapListById(model, "listWvFlowALL"));
	}

	@Override
	public void getSingleWvFlowInfo(WvFlow model) {
		if(model.getFlowUuid()==null||StringUtils.isEmpty(model.getFlowUuid().toString())){
			throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供流程UUID信息！");
		}
		
		JhCnd cnd=new JhCnd();
		cnd.andEquals("flowUuid");
		model.lnkCnd(cnd);
		List<Map<String,Object>> list=this.queryMapList(model);
		if(list==null||list.size()<=0||list.size()>1){
			throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"提供流程UUID信息有误,查询不到相关信息！");
		}
		Map<String,Object> objMap=list.get(0);
		if(objMap.get("code")==null){
			throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"提供流程编号信息有误,查询不到相关信息！");
		}
		WvProcessConfig wpModel=new WvProcessConfig();
		String code=objMap.get("code").toString();
		cnd.reset();
		cnd.andEquals("fcode");
		//cnd.append("w.process_id <> '' ")
		cnd.orderBy("w.sort", "asc");
		wpModel.setFcode(code);
		wpModel.lnkCnd(cnd);
		wpModel.setPage(null);
		List<Map<String,Object>> wvplist=this.wvProcessConfigService.queryMapListById(wpModel, "queryMapListProcessconfigByFcode");
		objMap.put("processInfoList", this.getWvProcessConfigList(wvplist));
		model.setMapList(list);	
 
		
	}
    /**
     * 获取环节数据
     * @param wvplist
     * @return
     */
	public List<Map<String,Object>> getWvProcessConfigList(List<Map<String,Object>> wvplist){
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		Set<String> dateSet=new HashSet<String>();
		String processId="";
		Map<String,Object> processMap=null;
		//第一步，获取环节数据
		for(Map<String,Object> map:wvplist){
			if(map.get("processId")==null){
				continue;
			}
			processId=map.get("processId").toString();
			if(!dateSet.contains(processId)){
				processMap=new HashMap<String,Object>();
				processMap.put("processId", processId);
				processMap.put("name", map.get("name")!=null?map.get("name").toString():"");
				dateSet.add(processId);
				//第二步，获取位置编码信息
				processMap.put("locationIdList", this.getWvProcessLocationIdList(wvplist,processId));
				list.add(processMap);
			}
		}
		dateSet.clear();
		return list;
		
	}
	/**
	 * 获取位置编码信息
	 * @param wvplist
	 * @param processId
	 * @return
	 */
	public List<Map<String,Object>> getWvProcessLocationIdList(List<Map<String,Object>> wvplist,String processId){
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		Set<String> dateSet=new HashSet<String>();
		String locationId="";
		Map<String,Object> locationMap=null;
		for(Map<String,Object> map:wvplist){
			if(map.get("locationId")==null){
				continue;
			}
			locationId=map.get("locationId").toString();
			if(!dateSet.contains(locationId)&&map.get("processId")!=null&&map.get("processId").toString().equals(processId)){
				locationMap=new HashMap<String,Object>();
				locationMap.put("locationId", locationId);
				locationMap.put("fcameraUuidList", this.getWvProcessdeviceIdList(wvplist, locationId,processId));
				dateSet.add(locationId);
				list.add(locationMap);
			}
		}
		return list;
	}
	/**
	 * 获取环节位置编码对应设备信息
	 * @param wvplist
	 * @param processId
	 * @return
	 */
	public List<Map<String,Object>> getWvProcessdeviceIdList(List<Map<String,Object>> wvplist,String locationId,String processId){
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		Set<String> dateSet=new HashSet<String>();
		String fcameraUuid="";
		Map<String,Object> fdeviceMap=null;
		for(Map<String,Object> map:wvplist){
			if(map.get("cameraUuid")==null){ 
				continue;
			}
			fcameraUuid=map.get("cameraUuid").toString();
			//if(map.get("status")!=null&&map.get("status").toString().equals(String.valueOf(EWvCamera.status_1))&&!dateSet.contains(locationId)&&map.get("locationId")!=null&&map.get("locationId").toString().equals(locationId)){
			if(!dateSet.contains(locationId)&&map.get("locationId")!=null&&map.get("locationId").toString().equals(locationId)&&map.get("processId").toString().equals(processId)){
				fdeviceMap=new HashMap<String,Object>();
				fdeviceMap.put("cameraUuid", fcameraUuid);
				fdeviceMap.put("deviceName", map.get("deviceName")!=null?map.get("deviceName").toString():"");
				list.add(fdeviceMap);
				dateSet.add(fcameraUuid);
			}
		}
		return list;
	}
	
	@Override
	public void addWvFlow(WvFlow model) {
		if(model.getObjMap()!=null){
		    Map<String,Object> flowMap=model.getObjMap();
		    Set<String> dateSet=new HashSet<String>();
		    Set<String> processIdSet=new HashSet<String>();
			//第一步：获取流程信息
			//Map<String,Object> flowMap=(Map)map.get("WvFlowInfo");
			WvFlow newModel=new WvFlow();
			if(flowMap.get("code")==null||StringUtils.isEmpty(flowMap.get("code").toString())){
				throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供流程编号信息！");
			}
			newModel.setCode(flowMap.get("code").toString());
			if(flowMap.get("name")==null||StringUtils.isEmpty(flowMap.get("name").toString())){
				throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供流程名称信息！");
			}
			newModel.setName(flowMap.get("name").toString());
			if(flowMap.get("status")==null){
				newModel.setStatus(EWvFlow.status_1.getKey());
				//throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供流程状态信息！");
			}else{
				newModel.setStatus(Integer.parseInt(flowMap.get("status").toString()));
			}
			if(flowMap.get("sort")==null){
				newModel.setSort(1);
				//throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供流程排序信息！");
			}else{
				newModel.setSort(Integer.parseInt(flowMap.get("sort").toString()));
			}
			String _uuid=this.checkWvFlowIsExists(flowMap.get("code").toString());
			if(_uuid!=null){
				throw new JingHaoCustomerException(EJhTwsCode.TWS3002.getCode(),"提供流程编号已存在，不允许重复添加！");
			}
			newModel.setFlowUuid(model.getUUID());
			newModel.setCreator("测试");
			newModel.setCreateTime(new Date());
			newModel.setStatus(EWvFlow.status_1.getKey());
			
			//第二步：获取环节信息
		    List<WvProcessConfig> pList=new ArrayList<WvProcessConfig>();
		    List<Map<String,Object>> mList=null;
		    List<Map<String,Object>> locationIdList=null;
		    List<String> fcameraUuidList=null;
		    WvProcessConfig wpModel=null;	
		    String tempProcessAndLoaction="";
		    int i=1;
		    if(flowMap.get("processInfoList")==null){
		    	throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供环节配置信息！");
		    }else{
		    	mList=(List<Map<String,Object>>)flowMap.get("processInfoList");
		    	for(Map<String,Object> tempMap:mList){
		    		if(tempMap.get("processId")==null||StringUtils.isEmpty(tempMap.get("processId").toString())){
						throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供环节编号信息！");
					}
    				if(processIdSet.contains(tempMap.get("processId").toString())){
    					throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"填写错误，提供了重复环节编号信息！【环节编号:"+tempMap.get("processId").toString()+"】");
    				}
    				processIdSet.add(tempMap.get("processId").toString());
		    		if(tempMap.get("name")==null||StringUtils.isEmpty(tempMap.get("name").toString())){
						throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供环节名称信息！");
					}
		    		if(tempMap.get("locationIdList")!=null){
		    			locationIdList=(List<Map<String,Object>>)tempMap.get("locationIdList");
		    			for(Map<String,Object> tempLocationMap:locationIdList){
		    				if(tempLocationMap.get("locationId")==null||StringUtils.isEmpty(tempLocationMap.get("locationId").toString())){
		    					throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供位置编码信息！");
		    				}
		    				tempProcessAndLoaction=tempMap.get("processId").toString()+"||"+tempLocationMap.get("locationId").toString();
		    				if(dateSet.contains(tempProcessAndLoaction)){
		    					throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"填写错误，在同一个环节中,提供了重复位置编码信息！【位置编码:"+tempLocationMap.get("locationId").toString()+"】");
		    				}
		    				dateSet.add(tempProcessAndLoaction);
		    				if(tempLocationMap.get("fcameraUuid")==null){
		    					throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供摄像头信息！");
		    				}
		    				fcameraUuidList=(List<String>)tempLocationMap.get("fcameraUuid");
		    				for(String fcameraUuid:fcameraUuidList){
		    					wpModel=new WvProcessConfig();
		    					wpModel.setProcessconfigUuid(model.getUUID());
		    					wpModel.setProcessId(tempMap.get("processId").toString());
		    					wpModel.setName(tempMap.get("name").toString());
		    					wpModel.setFcode(newModel.getCode());
		    					wpModel.setCreator("测试");
		    					wpModel.setCreateTime(new Date());
		    					wpModel.setSort(++i);
		    					wpModel.setLocationId(tempLocationMap.get("locationId").toString());
		    					wpModel.setFcameraUuid(fcameraUuid);
		    					pList.add(wpModel);
		    				}
		    			}
		    		}
		    	}
		    }	
		    //第三步：保存数据
		    this.add(newModel);
		    
		    //生成数据同步任务
		    this.addWvUploadTaskInfo(newModel);
		    
		    for(WvProcessConfig tempModel:pList){
		    	 this.wvProcessConfigService.add(tempModel);
		    }
			//第四步：清理数据
			flowMap.clear();
			newModel=null;
			pList.clear();
			wpModel=null;
			dateSet.clear();
			processIdSet.clear();
	    }
	}
	
	@Override
	public void updateWvFlow(WvFlow model) {
		if(model.getObjMap()!=null){
			Map<String,Object> flowMap=model.getObjMap();
			Set<String> dateSet=new HashSet<String>();
			Set<String> processIdSet=new HashSet<String>();
			
			    WvProcessConfig mvProcessConfie=new WvProcessConfig();
			    JhCnd cnd=new JhCnd();
				//第一步：获取流程信息
				WvFlow newModel=new WvFlow();
				if(flowMap.get("flowUuid")==null||StringUtils.isEmpty(flowMap.get("flowUuid").toString())){
					throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供流程UUID信息！");
				}
				newModel.setFlowUuid(flowMap.get("flowUuid").toString());
				newModel=this.get(newModel);
				 //先删除环节数据
			    cnd.reset();
			    cnd.andEquals("fcode");
			    mvProcessConfie.lnkCnd(cnd);
			    mvProcessConfie.setFcode(newModel.getCode());
			    this.wvProcessConfigService.deleteSame(mvProcessConfie);
			    
				if(flowMap.get("code")==null||StringUtils.isEmpty(flowMap.get("code").toString())){
					throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供流程编号信息！");
				}
				newModel.setCode(flowMap.get("code").toString());
				if(flowMap.get("name")==null||StringUtils.isEmpty(flowMap.get("name").toString())){
					throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供流程名称信息！");
				}
				newModel.setName(flowMap.get("name").toString());
				if(flowMap.get("status")==null){
					//newModel.setStatus(EWvFlow.status_1.getKey());
					//throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供流程状态信息！");
				}else{
					newModel.setStatus(Integer.parseInt(flowMap.get("status").toString()));
				}
				if(flowMap.get("sort")==null){
					//newModel.setSort(1);
					//throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供流程排序信息！");
				}else{
					newModel.setSort(Integer.parseInt(flowMap.get("sort").toString()));
				}
				String _uuid=this.checkWvFlowIsExists(flowMap.get("code").toString());
				if(_uuid!=null&&!_uuid.equals(newModel.getFlowUuid())){
					throw new JingHaoCustomerException(EJhTwsCode.TWS3002.getCode(),"提供流程编号已存在！");
				}
				newModel.setUpdater("测试");
				newModel.setUpdateTime(new Date());
				 
				//第二步：获取环节信息
			    List<WvProcessConfig> pList=new ArrayList<WvProcessConfig>();
			    List<Map<String,Object>> mList=null;
			    List<Map<String,Object>> locationIdList=null;
			    List<String> fcameraUuidList=null;
			    String tempProcessAndLoaction="";
			    WvProcessConfig wpModel=null;	
			    int i=1;
			    if(flowMap.get("processInfoList")==null){
			    	throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供环节配置信息！");
			    }else{
			    	mList=(List<Map<String,Object>>)flowMap.get("processInfoList");
			    	for(Map<String,Object> tempMap:mList){
			    		if(tempMap.get("processId")==null||StringUtils.isEmpty(tempMap.get("processId").toString())){
							throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供环节编号信息！");
						}
	    				if(processIdSet.contains(tempMap.get("processId").toString())){
	    					throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"填写错误，提供了重复环节编号信息！【环节编号:"+tempMap.get("processId").toString()+"】");
	    				}
	    				processIdSet.add(tempMap.get("processId").toString());
			    		if(tempMap.get("name")==null||StringUtils.isEmpty(tempMap.get("name").toString())){
							throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供环节名称信息！");
						}
			    		if(tempMap.get("locationIdList")!=null){
			    			locationIdList=(List<Map<String,Object>>)tempMap.get("locationIdList");
			    			for(Map<String,Object> tempLocationMap:locationIdList){
			    				if(tempLocationMap.get("locationId")==null||StringUtils.isEmpty(tempLocationMap.get("locationId").toString())){
			    					throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供位置编码信息！");
			    				}
			    				
			    				tempProcessAndLoaction=tempMap.get("processId").toString()+"||"+tempLocationMap.get("locationId").toString();
			    				if(dateSet.contains(tempProcessAndLoaction)){
			    					throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"填写错误，在同一个环节中,提供了重复位置编码信息！【位置编码:"+tempLocationMap.get("locationId").toString()+"】");
			    				}
			    				dateSet.add(tempProcessAndLoaction);			    				
			    				if(tempLocationMap.get("fcameraUuid")==null){
			    					throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供摄像头信息！");
			    				}
			    				fcameraUuidList=(List<String>)tempLocationMap.get("fcameraUuid");
			    				for(String fcameraUuid:fcameraUuidList){
			    					wpModel=new WvProcessConfig();
			    					wpModel.setProcessconfigUuid(model.getUUID());
			    					wpModel.setProcessId(tempMap.get("processId").toString());
			    					wpModel.setName(tempMap.get("name").toString());
			    					wpModel.setFcode(newModel.getCode());
			    					wpModel.setCreator("测试");
			    					wpModel.setCreateTime(new Date());
			    					wpModel.setSort(++i);
			    					wpModel.setLocationId(tempLocationMap.get("locationId").toString());
			    					wpModel.setFcameraUuid(fcameraUuid);
			    					pList.add(wpModel);
			    				}
			    			}
			    		}
			    	}
			    }	
			    //第三步：保存数据
			    //更新流程信息
			    cnd.reset();
			    cnd.andEquals("flowUuid");
			    newModel.lnkCnd(cnd);
			    JhUpdate update=new JhUpdate();
			    update.add("code").add("name").add("updater").add("updateTime");
			    newModel.setUpdateSet(update);
			    this.updateSame(newModel);
			    
			    //生成数据同步任务
			    this.addWvUploadTaskInfo(newModel);
			    
			    cnd.reset();
			    for(WvProcessConfig tempModel:pList){
			    	 this.wvProcessConfigService.add(tempModel);
			    }
				//第四步：清理数据
				flowMap.clear();
				newModel=null;
				pList.clear();
				wpModel=null;
				dateSet.clear();
				processIdSet.clear();
			}
	}

	/**
	 * 启用、禁用、删除流程（包含批量处理）
	 */
	@Override
	public void updateWvFlowStatic(WvFlow model) {
		if (model.getStatus()==null) {
			throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请提供流程状态信息！");
		}
		if(model.getStrList()==null||model.getStrList().size()<=0){
			throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"请选择流程相关记录信息！");
		}
		JhCnd cnd=new JhCnd();
		cnd.andIn("flowUuid", "strList", model.getStrList());
		if(model.getStatus().equals(EWvCamera.status_0.getKey())){
			cnd.append(" and status=1");
		}else if(model.getStatus().equals(EWvCamera.status_1.getKey())){
			cnd.append(" and status=0");
		}else if(model.getStatus().equals(EWvCamera.status_2.getKey())){
			cnd.append(" and status<>2");
		}else{
			throw new JingHaoCustomerException(EJhTwsCode.TWS3001.getCode(),"提供流程状态信息有误！");
		}
		model.lnkCnd(cnd);
		model.setUpdateTime(new Date());
		JhUpdate update=new JhUpdate();
		update.add("status").add("updateTime");
		model.setJhUpdate(update);
		this.updateSame(model); 
		
	}
	
	
	public void addWvUploadTaskInfo(WvFlow model){
		
		WvUploadTaskInfo wvTaskInfo=new WvUploadTaskInfo();
		//删除任务
		JhCnd cnd=new JhCnd();
		wvTaskInfo.setWorkUuid(model.getFlowUuid());
		wvTaskInfo.setTaskType(EWvUploadTaskInfo.taskType_2.getKey());
		cnd.andEquals("taskType");
	//	cnd.andEquals("workUuid");
		wvTaskInfo.setJhCnd(cnd);
		this.wvUploadTaskInfoService.deleteSame(wvTaskInfo);
		//保存视频任务生成
		//WvUploadTaskInfo wvTaskInfo=new WvUploadTaskInfo();
		wvTaskInfo.setTaskUuid(model.getUUID());
		wvTaskInfo.setCreateTime(new Date());
		wvTaskInfo.setTaskType(EWvUploadTaskInfo.taskType_2.getKey());
		wvTaskInfo.setWorkUuid(model.getFlowUuid());
		wvTaskInfo.setTaskLevel(EWvUploadTaskInfo.taskType_2.getKey());
		this.wvUploadTaskInfoService.add(wvTaskInfo);
	}
	
	//==================定制内容结束======================
}
